<?php

namespace App\Rules;

use App\Rules\Concerns\AttributeNormalize;
use Illuminate\Contracts\Validation\Rule;

/**
 * Class DeepRequired
 *
 * @package App\Rules
 */
class DeepRequired implements Rule
{
    use AttributeNormalize;
    /**
     * @var string
     */
    protected $attribute;

    /**
     * @var bool
     */
    private $nullable;

    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value): bool
    {
        $this->attribute = $attribute;

        return $this->isDeepFilled($value);
    }


    /**
     * @param array|string|null $value
     *
     * @return bool
     */
    private function isDeepFilled($value): bool
    {
        if (is_array($value)) {
            foreach ($value as $idx => $val) {
                if (! ($this->isDeepFilled($idx) && $this->isDeepFilled($val))) {
                    return false;
                }
            }
            return true;
        } else {
            return filled($value);
        }
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        $attr_name = $this->attributeValidationKey($this->attribute);

        return trans('validation.deep_required', ['attribute' => $attr_name]);
    }

}
